package com.atwork.wuhua.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.atwork.wuhua.ConstantsMyself;
import com.atwork.wuhua.R;
import com.atwork.wuhua.base.BaseFragment;
import com.atwork.wuhua.dialog.AutographEditTextDialog;
import com.atwork.wuhua.dialog.BaseDialog;
import com.atwork.wuhua.dialog.CenterEditTextDialog;
import com.atwork.wuhua.mvp.presenter.MyPresenter;
import com.atwork.wuhua.mvp.view.IMyFragment;
import com.atwork.wuhua.ui.activity.FeedbackActivity;
import com.atwork.wuhua.ui.activity.KefuActivity;
import com.atwork.wuhua.ui.activity.MyCollectionActivity;
import com.atwork.wuhua.ui.activity.MyFollowActivity;
import com.atwork.wuhua.ui.activity.MyWarActivity;
import com.atwork.wuhua.ui.activity.SetUpActivity;
import com.atwork.wuhua.utils.GlideUtils.GlideUtil;
import com.atwork.wuhua.utils.LogUtils;
import com.atwork.wuhua.utils.UserUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MyFragment extends BaseFragment implements IMyFragment {

    Unbinder unbinder;
    @BindView(R.id.img_thumb)
    ImageView imgThumb;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_autograph)
    TextView tvAutograph;
    @BindView(R.id.tv_follow)
    TextView tvFollow;
    @BindView(R.id.tv_fensi)
    TextView tvFensi;

    private TimePickerView pvTime1;
    private OptionsPickerView pvOptions;

    private MyPresenter presenter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    public int intiLayout() {
        return R.layout.fragment_my;
    }

    @Override
    public void initView() {

        presenter = new MyPresenter();
        presenter.attachView(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserUtil.isLogin(getActivity())) {
            GlideUtil.loadCircleThumb(getActivity(), UserUtil.getHeadIcon(getActivity()), imgThumb);
            tvName.setText(UserUtil.getNickname(getActivity()));
            tvPhone.setText(UserUtil.getUserBean(getActivity()).getData().getMobile());
            if (UserUtil.getUserBean(getActivity()).getData().getGender().equals("1")) {
                tvSex.setText("男");
            } else {
                tvSex.setText("女");
            }
            tvBirthday.setText(UserUtil.getUserBean(getActivity()).getData().getBirth());
            tvAutograph.setText(UserUtil.getUserBean(getActivity()).getData().getSignature());
        } else {
            imgThumb.setImageDrawable(getResources().getDrawable(R.mipmap.icon_avath));
            tvName.setText("请登录");
            tvPhone.setText("");
            tvSex.setText("");
            tvBirthday.setText("");
            tvAutograph.setText("");
        }

    }

    @Override
    public void initData() {
        initTimePicker1();
        initSexPicker();
    }


    @OnClick({R.id.tv_my_collection, R.id.tv_my_message, R.id.img_setup, R.id.tv_my_sub, R.id.tv_my_war, R.id.rly_phone, R.id.rly_sex, R.id.rly_birthday, R.id.rly_kefu, R.id.rly_feedback, R.id.img_thumb, R.id.rly_name,
            R.id.tv_follow, R.id.tv_fensi, R.id.rly_autograph})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.tv_follow:
                intent = new Intent(getActivity(), MyFollowActivity.class);
                intent.putExtra(ConstantsMyself.INTENTTYPE, MyFollowActivity.FOLLOW);
                startActivity(intent);
                break;
            case R.id.tv_fensi:
                intent = new Intent(getActivity(), MyFollowActivity.class);
                intent.putExtra(ConstantsMyself.INTENTTYPE, MyFollowActivity.FANS);
                startActivity(intent);
                break;
            case R.id.tv_my_collection:
                intent = new Intent(getActivity(), MyCollectionActivity.class);
                intent.putExtra(ConstantsMyself.INTENTTYPE, MyCollectionActivity.COLLECTION);
                startActivity(intent);
                break;
            case R.id.tv_my_message:
                intent = new Intent(getActivity(), MyCollectionActivity.class);
                intent.putExtra(ConstantsMyself.INTENTTYPE, MyCollectionActivity.MESSAGE);
                startActivity(intent);
                break;
            case R.id.img_thumb:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    PictureSelector.create(this)
                            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                            .maxSelectNum(1)// 最大图片选择数量 int
                            .minSelectNum(1)// 最小选择数量 int
                            .imageSpanCount(3)// 每行显示个数 int
                            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .previewImage(true)// 是否可预览图片 true or false
                            .previewVideo(false)// 是否可预览视频 true or false
                            .enablePreviewAudio(false) // 是否可播放音频 true or false
                            .isCamera(true)// 是否显示拍照按钮 true or false
                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                            .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                            .enableCrop(true)// 是否裁剪 true or false
                            .compress(true)// 是否压缩 true or false
                            .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                            .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                            .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                            .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                            .openClickSound(false)// 是否开启点击声音 true or false
                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                            .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                            .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                            .isDragFrame(true)// 是否可拖动裁剪框(固定)
                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                }
                break;
            case R.id.img_setup:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    intent = new Intent(mActivity, SetUpActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.tv_my_sub:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    intent = new Intent(mActivity, MyWarActivity.class);
                    intent.putExtra(ConstantsMyself.INTENTTYPE, MyWarActivity.MYSUB);
                    startActivity(intent);
                }
                break;
            case R.id.tv_my_war:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    intent = new Intent(mActivity, MyWarActivity.class);
                    intent.putExtra(ConstantsMyself.INTENTTYPE, MyWarActivity.MYWAR);
                    startActivity(intent);
                }

                break;
            case R.id.rly_phone:
                break;
            case R.id.rly_sex:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    pvOptions.show();

                }
                break;
            case R.id.rly_birthday:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    pvTime1.show();

                }
                break;
            case R.id.rly_kefu:
                intent = new Intent(mActivity, KefuActivity.class);
                startActivity(intent);
                break;
            case R.id.rly_feedback:
                intent = new Intent(mActivity, FeedbackActivity.class);
                startActivity(intent);

                break;
            case R.id.rly_name:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    CenterEditTextDialog centerEditTextDialog = new CenterEditTextDialog(getActivity(), new BaseDialog.OnEdDialogClick() {
                        @Override
                        public void dialogClick(String name, int switchButton) {
                            presenter.editInfo(name, "", "", "", "");
                        }


                    });
                    centerEditTextDialog.show();
                }

                break;
            case R.id.rly_autograph:
                if (UserUtil.isLoginOrOpen(getActivity())) {
                    AutographEditTextDialog autographEditTextDialog = new AutographEditTextDialog(getActivity(), new BaseDialog.OnEdDialogClick() {
                        @Override
                        public void dialogClick(String name, int switchButton) {
                            presenter.editInfo("", "", "", "", name);
                        }

                    });
                    autographEditTextDialog.show();
                }

                break;

        }
    }


    @Override
    public void editInfoResult() {
        GlideUtil.loadCircleImg(getActivity(), UserUtil.getHeadIcon(getActivity()), imgThumb);
        tvName.setText(UserUtil.getNickname(getActivity()));
        tvPhone.setText(UserUtil.getUserBean(getActivity()).getData().getMobile());
        if (UserUtil.getUserBean(getActivity()).getData().getGender().equals("1")) {
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
        tvBirthday.setText(UserUtil.getUserBean(getActivity()).getData().getBirth());
        tvAutograph.setText(UserUtil.getUserBean(getActivity()).getData().getSignature());
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        if (selectList.get(i).isCut() == true) {
                            LogUtils.e("path==>" + selectList.get(i).getCutPath());
                            GlideUtil.loadCircleImg(getActivity(), selectList.get(i).getCutPath(), imgThumb);
                            presenter.uploadImg(selectList.get(i).getCutPath());
                        }
                    }

                    break;
            }
        }
    }

    private void initTimePicker1() {
        //选择出生年月日
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        SimpleDateFormat formatter_year = new SimpleDateFormat("yyyy ");
        String year_str = formatter_year.format(curDate);
        int year_int = (int) Double.parseDouble(year_str);


        SimpleDateFormat formatter_mouth = new SimpleDateFormat("MM ");
        String mouth_str = formatter_mouth.format(curDate);
        int mouth_int = (int) Double.parseDouble(mouth_str);

        SimpleDateFormat formatter_day = new SimpleDateFormat("dd ");
        String day_str = formatter_day.format(curDate);
        int day_int = (int) Double.parseDouble(day_str);


        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year_int, mouth_int - 1, day_int);

        //时间选择器
        pvTime1 = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                /*btn_Time.setText(getTime(date));*/
                tvBirthday.setText(getTime(date));
                presenter.editInfo("", "", "", getTime(date) + "", "");
                LogUtils.e("time==>" + getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .build();
    }

    private void initSexPicker() {
        final List<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        //条件选择器
        pvOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String gender = null;
                tvSex.setText(sexList.get(options1));
                if (sexList.get(options1).equals("男")) {
                    gender = "1";
                } else {
                    gender = "2";
                }
                presenter.editInfo("", gender, "", "", "");
            }
        }).build();
        pvOptions.setPicker(sexList);

    }


    private String getTime(Date date) {
        //可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        return format.format(date);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
